package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    public String list(@RequestParam Map<String, String> searchMap, Model model) {

        //查询结果
        Map<String, Object> resultMap = searchService.searchQuery(searchMap);

        //封装数据
        model.addAttribute("searchMap", searchMap);
        model.addAttribute("resultMap", resultMap);

        //封装分页数据并返回
        //总记录数
        //当前页
        //每页显示多少条
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),
                Page.pageSize
        );

        model.addAttribute("page", page);

        //拼装url
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0) {
            //有查询条件
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if (!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)) {
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }
            String urlString = url.toString();
            //去除路径上的最后一个&
            urlString = urlString.substring(0, urlString.length() - 1);
            model.addAttribute("url", urlString);
        } else {
            model.addAttribute("url", url);
        }

        return "search";
    }

    //用户搜索商品
    @RequestMapping("/find")
    @ResponseBody
    public Result search(@RequestParam Map<String, String> searchMap) {
        Map<String, Object> data = searchService.searchQuery(searchMap);
        Set<String> keySet = data.keySet();
        for (String s : keySet) {
            System.out.println(s + ":" + data.get(s));
        }

        return new Result(true, StatusCode.OK, "搜索数据成功", data);
    }


//    //展示商品
//    @RequestMapping("/findAll")
//    @ResponseBody
//    public Result findAll() {
//        Map<String, Object> all = searchService.findAll();
//        return new Result(true, StatusCode.OK, "查询成功", all);
//    }

}
